package com.pay.web;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
 * Created by Administrator on 2017-7-4.
 * download files
 */

public class DownloadServlet extends HttpServlet {
    /**
     * download files
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获得要下载的文件名称
        String fileName = req.getParameter("fileName");
        fileName = new String(fileName.getBytes("iso8859-1"),"UTF-8");

        //获取下载路径
        String fileSaveRootPath = this.getServletContext().getRealPath("/WEB-INF/upload");
        //文件下载完整路径
        File file = new File(fileSaveRootPath + "\\" +fileName);
        System.out.println("======>> 完整路径:"+fileSaveRootPath + "\\" +fileName);
        //处理文件不存在
        if(null == file){
            req.setAttribute("message","文件不存在！");
            req.getRequestDispatcher("/WEB-INF/view/message.jsp").forward(req,resp);
            return;
        }

        //处理文件名
        String realName = fileName.substring(fileName.indexOf("_") + 1);
        System.out.println("fileName = "+fileName+",realName = "+realName);
        //设置响应头
        resp.setHeader("content-disposition","attachment;filename=" + URLEncoder.encode(realName, "UTF-8"));
        //读取要下载的文件，保存在文件输入流
        FileInputStream fileInputStream = new FileInputStream(file);
        //创建输出流
        OutputStream outputStream = resp.getOutputStream();
        byte buffer[] = new byte[1024];
        int len = 0;
        while ((len = fileInputStream.read(buffer))>0){
            outputStream.write(buffer,0,len);
        }
        fileInputStream.close();
        outputStream.close();
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}
